<template>
  <div>
    <BasicModal
      v-bind="$attrs"
      :title="title"
      @register="register"
      @ok="handleSubmit"
      @cancel="handleCancel"
      :destroyOnClose="true"
      :minHeight="600"
      :width="1000"
    >
      <Tabs v-model:activeKey="activeKey">
        <TabPane v-for="item in tabList" :key="item.propertyPageId" :tab="item.propertyPageName">
          <BasicForm @register="registerForm" :schemas="item.propertyTeams" />
        </TabPane>
      </Tabs>
    </BasicModal>
  </div>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Tabs, TabPane } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { GetBdInfoBeforeAdd, AddDocForm, OpenDocForm, EditDocForm } from '/@/api/demo/document';

  const { t } = useI18n();
  const emit = defineEmits(['register', 'success']);
  const { createMessage } = useMessage();
  const title = ref('');
  const tabList = ref<any>([]);
  const activeKey = ref('');
  const selectedDirKey = ref('');
  const fileType = ref('');
  const type = ref('');
  const typeName = ref('');

  // 提交表单
  const handleSubmit = async () => {
    const values = await validate();
    if (!!values) {
      let newKey = Object.keys(getFieldsValue());
      let params = newKey.map((key) => ({
        id: key,
        value: getFieldsValue()[key],
      }));
      if (type.value == '新增') {
        AddDocForm(selectedDirKey.value, fileType.value, params)
          .then((res) => {
            if (res) {
              createMessage.success(t('common.successText'));
              emit('success');
              closeModal();
            }
          })
          .catch((err) => {
            createMessage.error(err.message);
            setModalProps({ confirmLoading: false });
            handleCancel();
          });
      } else if (type.value == '查看') {
        EditDocForm(typeName.value, params)
          .then((res) => {
            if (res) {
              createMessage.success(t('common.successText'));
              emit('success');
              closeModal();
            }
          })
          .catch((err) => {
            createMessage.error(err.message);
            setModalProps({ confirmLoading: false });
            handleCancel();
          });
      }
    }
  };

  // 关闭弹窗
  const handleCancel = () => {
    closeModal();
  };

  function convertDataFormat(data) {
    let result = [];

    // 遍历第一种数据格式的每个对象
    data.forEach((page) => {
      let convertedPage = {
        propertyPageId: page.propertyPageId,
        propertyPageName: page.propertyPageName,
        propertyTeams: [],
      };

      // 遍历 propertyTeamlst 数组
      page.propertyTeamlst.forEach((team) => {
        let convertedTeam = [];
        let dividerComponent = {
          field: team.propertyTeamId,
          label: team.propertyTeamName,
          component: 'Divider',
        };
        convertedTeam.push(dividerComponent);
        // 遍历 propertylst 数组
        team.propertylst.forEach((property) => {
          let convertedProperty = {
            field: property.propertyId,
            label: property.propertyName,
            component: getPropertyComponent(property.propertyType), // 根据 propertyType 设置对应的组件类型，这里需要根据你的具体需求处理
            defaultValue:
              type.value == '新增' && property.propertyType == 'select'
                ? ''
                : property.defaultValue,
            // pdmnull === 0 表示非必填，设置为 true 或 false，源文件名和文件类型做特殊判断
            required:
              property.propertyId != 'filename' &&
              property.propertyId != 'filetype' &&
              property.pdmnull === 0,
            colProps: {
              span: parseInt(property.col),
            },
            componentProps: {
              options: property.dataSource.map((item) => {
                return {
                  label: item.name,
                  value: item.id,
                };
              }),
              disabled:
                type.value === '新增'
                  ? property.propertyId === 'oid' ||
                    property.propertyId === 'version' ||
                    property.propertyId === 'creater' ||
                    property.propertyId === 'createtime' ||
                    property.propertyId === 'filetype' ||
                    property.propertyId === 'securitylevel' ||
                    property.propertyId === 'status' ||
                    property.propertyId === 'filename'
                  : type.value === '查看' &&
                    (property.propertyId === 'oid' ||
                      property.propertyId === 'version' ||
                      property.propertyId === 'creater' ||
                      property.propertyId === 'createtime' ||
                      property.propertyId === 'filetype' ||
                      property.propertyId === 'securitylevel' ||
                      property.propertyId === 'status' ||
                      property.propertyId === 'filename' ||
                      property.propertyId === 'ThitObjectId'),
            },
          };
          convertedTeam.push(convertedProperty);
        });
        convertedPage.propertyTeams.push(convertedTeam);
      });

      result.push(convertedPage);
    });

    return result;
  }

  // 辅助函数，根据不同的 propertyType 返回对应的组件类型
  function getPropertyComponent(propertyType) {
    switch (propertyType) {
      case 'varchar':
        return 'Input'; // 示例中假设 varchar 对应 Input 组件
      case 'int':
        return 'InputNumber'; // 示例中假设 int 对应 InputNumber 组件
      case 'datetime':
        return 'DatePicker'; // 示例中假设 datetime 对应 DatePicker 组件
      case 'select':
        return 'Select'; // 示例中假设 select 对应 Select 组件
      default:
        return 'Input'; // 默认使用 Input 组件
    }
  }

  // 初始化弹窗
  const [register, { setModalProps, closeModal }] = useModalInner((data) => {
    setModalProps({ confirmLoading: false });
    selectedDirKey.value = data.selectedDirKey;
    fileType.value = data.fileType;
    type.value = data.type;
    typeName.value = data.typeName;
    if (data.type == '新增') {
      // 根据文件类型获取表单配置
      GetBdInfoBeforeAdd(data.fileType).then((res) => {
        if (res !== null) {
          tabList.value = convertDataFormat(res);
          activeKey.value = tabList.value.length > 0 ? tabList.value[0].propertyPageId : '';
          tabList.value = tabList.value.map((item) => ({
            ...item,
            propertyTeams: item.propertyTeams.flat(),
          }));
        }
      });
    } else if (data.type == '查看') {
      OpenDocForm(data.oid, data.typeName, data.version).then((res) => {
        if (res !== null) {
          tabList.value = convertDataFormat(res);
          activeKey.value = tabList.value.length > 0 ? tabList.value[0].propertyPageId : '';
          tabList.value = tabList.value.map((item) => ({
            ...item,
            propertyTeams: item.propertyTeams.flat(),
          }));
        }
      });
    }
  });
  const [registerForm, { validate, getFieldsValue }] = useForm({
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
    showActionButtonGroup: false,
  });
</script>

<style scoped></style>
